package com.nanshenycd.controller.front;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nanshenycd.dao.ViewDao;
import com.nanshenycd.pojo.Comment;
import com.nanshenycd.pojo.Tag;
import com.nanshenycd.pojo.Type;
import com.nanshenycd.pojo.View;
import com.nanshenycd.service.*;
import com.nanshenycd.vo.DetailedBlog;
import com.nanshenycd.vo.FirstPageBlog;
import com.nanshenycd.vo.RecommendBlog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.concurrent.TimeUnit;

//index  html  页面缓存
//
//index:+id             URL缓存
@Controller
@Api(description  = "前台首页接口")
public class IndexController {
    @Autowired
    BlogService blogService;
    @Autowired
    TagService tagService;
    @Autowired
    TypeService typeService;
    @Autowired
    CommentService commentService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ViewDao viewsDao;

    @Autowired
    private ViewsService viewsService;

    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

    @GetMapping(value = "/")
    @ApiOperation(value = "首页默认路径渲染")
    public String hello(){
        return "hello";
    }


    @GetMapping(value = "/index",produces = "text/html;charset=utf-8")
    @ApiOperation(value = "首页默认路径渲染")
    @ResponseBody
    public String index(Model model, @RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum,
                        HttpServletRequest request, HttpServletResponse response) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String) valueOperations.get("index:" );
        if(!StringUtils.isEmpty(html)){
            return html;
        }
        //分页逻辑
        PageHelper.startPage(pageNum, 6);
        List<FirstPageBlog> firstPageBlog = blogService.getAllFirstPageBlog();
        List<Type> allType = typeService.getAllType();
        List<Tag> allTag = tagService.getAllTag();
        List<RecommendBlog> recommendBlog= blogService.getRecommendedBlog();
        PageInfo<FirstPageBlog> pageInfo= new PageInfo<>(firstPageBlog);
        //传入数据
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("types",allType);
        model.addAttribute("tags",allTag);
        model.addAttribute("recommendedBlogs",recommendBlog);
        /***
         * 手动渲染缓存
         */
        WebContext context = new WebContext(request,response,request.getServletContext(),
                request.getLocale(),model.asMap());

        html=thymeleafViewResolver.getTemplateEngine().process("index",context);
//        System.out.println(html);
        if(!StringUtils.isEmpty(html)){
            valueOperations.set("index",html,100, TimeUnit.SECONDS);
        }
//        System.out.println("手动渲染缓存结束");
        return html;
    }

    @PostMapping("/search")
    @ApiOperation(value = "首页搜索")
    public String search(Model model,@RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum,
                         @RequestParam String query){
        PageHelper.startPage(pageNum,100);
        List<FirstPageBlog> searchBlog  = blogService.getSearchBlog(query);

        PageInfo<FirstPageBlog> pageInfo = new PageInfo<>(searchBlog);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("query",query);

        return "search";
    }


    @GetMapping(value = "/blog/{id}",produces = "text/html;charset=utf-8")
    @ApiOperation(value = "根据id显示博客接口")
    @ResponseBody
    public String blog(@PathVariable Long id,Model model,HttpServletResponse response,HttpServletRequest request){
            /**
             * 博客点击量
             */
            Long count = viewsService.findCountById(id);
            System.out.println("博客点击量："+count);
            /***
             * 添加URL级缓存，优化博查询效率
             */
            ValueOperations valueOperations = redisTemplate.opsForValue();
            String blog = (String) valueOperations.get("blog:"+id);
            if(!StringUtils.isEmpty(blog)){
                return blog;
            }
            /**
             * 对象级别缓存
             */
            DetailedBlog detailedBlog = blogService.getDetailedBlog(id);
            List<Comment> comments= commentService.listCommentByBlogId(id);
            model.addAttribute("blog",detailedBlog);
            model.addAttribute("comments",comments);
            /**
             * 添加博客详情信息
             */
            View views = viewsDao.selectViewsById(id);
            views.setCount(count);//redis实现文章点击量
            model.addAttribute("view",views);
            /***
             * 手动渲染
             */
            WebContext context = new WebContext(request,response,request.getServletContext(),
                    request.getLocale(),model.asMap());
            blog=thymeleafViewResolver.getTemplateEngine().process("blog",context);
            /***
             * 设置100s一次缓存刷新
             */
            if(!StringUtils.isEmpty(blog)){
                valueOperations.set("blog:"+id,blog,100, TimeUnit.SECONDS);
            }
            return blog;
    }
}
